package com.example.administrator.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.SupportMapFragment;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.GeoPoint;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.administrator.test.fragment.FragmentSpecial;
import com.example.administrator.test.overlayutil.PoiOverlay;
import com.example.administrator.test.selectc.SelectCityActivity;

import java.util.List;

public class PoiSearchActivity extends AppCompatActivity implements OnGetSuggestionResultListener,OnGetPoiSearchResultListener {
    private AutoCompleteTextView actKey;
    private TextView tvCity,tv_route_end_cancel;
    private SuggestionSearch mSuggestion;//建议搜索的对象
    private ArrayAdapter<String> adapter;
    private PoiSearch poiSearch;//poi检索的对象
    private int currentPage=1;
    private BaiduMap baiduMap;//获取百度地图管理对象
    private String adress;
    private RelativeLayout rl_poiSearch;
    private Intent intent;
    private Button btn;
    private SuggestionResult.SuggestionInfo info;
    private SupportMapFragment fragment;
    private static double longitude;
    private static double latitude;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_poisearch);
        initView();
    }
    // 初始化方法
    public void initView(){
        btn= (Button) findViewById(R.id.search);//搜索按钮
        btn.getBackground().setAlpha(255);//设置搜索按钮背景为透明
        rl_poiSearch= (RelativeLayout) findViewById(R.id.rl_poiSearch);
        tvCity= (TextView) findViewById(R.id.city);//显示城市
        rl_poiSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent=new Intent(PoiSearchActivity.this,SelectCityActivity.class);
                startActivity(intent);
            }
        });
        tv_route_end_cancel= (TextView) findViewById(R.id.tv_route_end_cancel);
        //点击取消返回上一级界面
        tv_route_end_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();

            }
        });
        //从选择城市界面跳转回PoiSearchActivity界面，传参数
        intent=getIntent();
        adress=intent.getStringExtra("adress");
        tvCity.setText(adress);
        actKey= (AutoCompleteTextView) findViewById(R.id.searchkey);
        //获取建议搜索的实例对象
        mSuggestion= SuggestionSearch.newInstance();
        //根据城市以及关键字获取到建议结果后触发的监听事件
        mSuggestion.setOnGetSuggestionResultListener(this);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        actKey.setAdapter(adapter);
        //因为文本改变时 实时搜索建议 所以绑定AutoCompleteTextView文本改变监听
        actKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String city=tvCity.getText().toString().trim();
                String key=actKey.getText().toString().trim();
                // city!=null && !"".equals(city)
                if(TextUtils.isEmpty(city) || TextUtils.isEmpty(key)){
                    return;
                }
                //创建条件
                SuggestionSearchOption option=new SuggestionSearchOption();
                option.city(city);
                option.keyword(key);
                //发起建议
                mSuggestion.requestSuggestion(option);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        fragment= (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        baiduMap=fragment.getBaiduMap();
        poiSearch= PoiSearch.newInstance();//实例化检索对象
    }

    /**
     * 当执行 mSuggestion.requestSuggestion(option); 请求搜索建议时 获取到建议结果时回调的函数
     * @param suggestionResult 建议的结果
     */
    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
         //表示判断是否存在建议结果 并且建议结果未有异常
         if(suggestionResult==null || suggestionResult.error==
                 SuggestionResult.ERRORNO.RESULT_NOT_FOUND){
             return;
         }
         if(suggestionResult.error==SuggestionResult.ERRORNO.NO_ERROR){
             //在建议的结果对象中获取所有的建议结果集合
            List<SuggestionResult.SuggestionInfo> allSuggestions=
                    suggestionResult.getAllSuggestions();
             if(info!=null){
                 for(SuggestionResult.SuggestionInfo info:allSuggestions){
                     String key=info.key;//获取搜索关键字的名称
                     adapter.add(key);
                 }
             }
             adapter.notifyDataSetChanged();
         }
    }
    /**
     * 点击按钮执行poi搜索
     * @param view
     */
    public void searchButtonProcess(View view){
        String city=adress;
        String keyWord=actKey.getText().toString();
        if(TextUtils.isEmpty(city) || TextUtils.isEmpty(keyWord)){
            return;
        }
//        poiSearch.searchInBound(PoiBoundSearchOption)  根据指定的区域进行搜索
//        附近搜索
//        PoiNearbySearchOption option=new PoiNearbySearchOption();
//        option.keyword("美食");
//        option.location(new LatLng());
//        option.radius(500);
//        poiSearch.searchNearby(option);

        //创建城市内搜索的条件对象
        PoiCitySearchOption option=new PoiCitySearchOption();
        option.city(city);//搜索城市
        option.keyword(keyWord);//关键字
        option.pageCapacity(10);//搜索返回的每页显示的poi结果数量
        option.pageNum(currentPage);//设置当前页码
        //城市内搜索
        poiSearch.searchInCity(option);
        //设置poi检索查询获取结果的监听器
        poiSearch.setOnGetPoiSearchResultListener(this);
    }
    /**
     * 只要PoiSearch对象调用searchInCity()searchNearby()searchInBound()
     *  启动查询获取检索结果时回调的函数
     * @param poiResult poi检索的结果
     *    获取查询结果－－－添加到图层－－－图层添加到地图中
     */
    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if(poiResult.error== SearchResult.ERRORNO.NO_ERROR){
            //清空地图上原有的覆盖物
//            baiduMap.clear();
            // 创建图层对象
            MyPoiOverly overly=new MyPoiOverly(baiduMap);
            //详细查询  将overly图层中的结果点绑定单击事件
            baiduMap.setOnMarkerClickListener(overly);
            //设置图层对象中展示的数据
            overly.setData(poiResult);
            //将图层添加到地图上
            overly.addToMap();
            //设置地图的缩放
            overly.zoomToSpan();
        }
    }
    /**
     * 以内部类的形式自定义展示poi检索结果的图层对象
     */
    class MyPoiOverly extends PoiOverlay {
        /**
         * 构造函数
         * @param baiduMap 该 PoiOverlay 引用的 BaiduMap 对象
         */
        public MyPoiOverly(BaiduMap baiduMap) {
            super(baiduMap);
        }

        /**
         * 调用baiduMap.setOnMarkerClickListener(overly);给结果点绑定单击事件时 会回调
         * PoiOverlay中的onPoiClick方法
         * @param i 表示poi结果中点击标记点的下标
         */
        @Override
        public boolean onPoiClick(int i) {
            PoiResult poiResult=getPoiResult();//获取所有的poi检索结果
            List<PoiInfo> allPoi=poiResult.getAllPoi();//将poi检索结果转换成list集合
            PoiInfo poiInfo=allPoi.get(i);//根据用户点击下标获取点的对象

            //创建详细查询的条件对象
            PoiDetailSearchOption option=new PoiDetailSearchOption();
            option.poiUid(poiInfo.uid);//设置当前查询的标记点的uid 唯一标示
            //针对每个标记点进行详细查询
            poiSearch.searchPoiDetail(option);
            return true;
        }
    }
    /**
     * poiSearch.searchPoiDetail(option);针对每个标记点查询的方法
     * 回调onGetPoiDetailResult()方法  获取poi详细查询结果
     * @param poiDetailResult  poi检索的详情结果
     */
    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if(poiDetailResult.error== SearchResult.ERRORNO.NO_ERROR){
//            String address=poiDetailResult.getAddress();
            String name=poiDetailResult.getName();
            //获取点击标记点的经纬度
            LatLng latLng=poiDetailResult.getLocation();
            latitude = latLng.latitude;
            longitude = latLng.longitude;
            Log.i("tag","-----------------------------"+"纬度："+latitude+"经度："+longitude+"----------------------");

//            String phone=poiDetailResult.getTelephone();
//            double price=poiDetailResult.getPrice();
//            String hours=poiDetailResult.getShopHours();
//            Toast.makeText(PoiSearchActivity.this,"商家名称:"+name+",地址:"+address+",电话:"+phone
//                        +",人均消费:"+price+",营业时间:"+hours,Toast.LENGTH_LONG).show();
            intent=new Intent(PoiSearchActivity.this,MainActivity.class);
            intent.putExtra("endAdress",name);
            intent.putExtra("tag",1);//设置标志位
            startActivity(intent);
        }
    }

    //下一页数据
    public void goToNextPage(View view){
        currentPage++;
        searchButtonProcess(null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
    public static double getLatitude(){
        return latitude;
    }
    public static double getLongitude(){
        return longitude;
    }
    
}













